package com.tryaging.aspect;

import com.tryaging.anno.ReTry;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author CKC
 * @DateTime 2021/11/21 13:02
 */
@Aspect
@Component
public class AspectJ {
    private static final Logger logger = LoggerFactory.getLogger(AspectJ.class);

    @Around("@annotation(com.tryaging.anno.ReTry)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long startTime = System.currentTimeMillis();
        Method method = ((MethodSignature) point.getSignature()).getMethod();
        ReTry reTry = method.getAnnotation(ReTry.class);
        int value = reTry.value();
        int count = 0;
        long timeout = reTry.timeout();
        long start = System.currentTimeMillis();
        Object result = null;
        while (count++ <= value) {
            result = point.proceed();
            if (count != 1) {
                logger.info(method.getName() + "\t第" + (count - 1) + "次重试");
                Thread.yield();
            }
            long end = System.currentTimeMillis();
            if (result != null || end - start > timeout) {
                break;
            }
        }
        logger.info("用时：" + (System.currentTimeMillis() - startTime) / 1000 + "s");
        return result;
    }
}
